package com.xbongbong.saas.factory.publicrule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.enums.errorcodes.CustomerErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.domain.entity.CustomerRuleEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Objects;

/**
 * 最大拥有客户数规则校验、数据获取类
 *
 * @author : chy
 * @version v3.22
 * @date 创建时间：2018-5-16 下午4:24:22
 */
public class OperateMaxCustomerNumRuleValue implements IOperateRuleValue {

    private static final Logger LOG = LoggerFactory.getLogger(OperateMaxCustomerNumRuleValue.class);

    @Override
    public void verify(String ruleValue) throws XbbException {
        JSONObject ruleObject = null;
        try {
            ruleObject = JSON.parseObject(ruleValue);
        } catch (Exception e) {
            // ignore
        }

        JSONArray restrict;
        JSONObject backRule;
        Integer type;
        Integer contract;
        Integer opportunity;
        JSONArray customerStatus;

        if (ruleObject == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }
        try {
            type = ruleObject.getInteger("type");
            contract = ruleObject.getInteger("contract");
            opportunity = ruleObject.getInteger("opportunity");
            customerStatus = ruleObject.getJSONArray("customerStatus");
            restrict = ruleObject.getJSONArray("restrict");
            backRule = ruleObject.getJSONObject("backRule");
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }

        boolean isNotType = !Objects.equals(type, 0) && !Objects.equals(type, 1) && !Objects.equals(type, 2) && !Objects.equals(type, 3);
        if (type == null || isNotType) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015, ErrorMessageConstant.SETTING_TYPE_ERROR);
        }

        boolean isNotContract = !Objects.equals(contract, 0) && !Objects.equals(contract, 1);
        if (contract == null || isNotContract) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015, ErrorMessageConstant.CONTRACT_TYPE_ERROR);
        }

        boolean isNotOpportunity = !Objects.equals(opportunity, 0) && !Objects.equals(opportunity, 1);
        if (opportunity == null || isNotOpportunity) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015, ErrorMessageConstant.SALE_TYPE_ERROR);
        }

        if (customerStatus == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015, ErrorMessageConstant.CUSTOMER_STATUS_ERROR);
        }

        if (restrict == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }


        for (Object restrictObject : restrict) {
            JSONObject restrictJson;
            JSONArray array;
            JSONArray users;

            try {
                restrictJson = (JSONObject) restrictObject;
                array = restrictJson.getJSONArray("array");
                users = restrictJson.getJSONArray("users");
            } catch (Exception e) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
            }

            if (users != null && users.size() == 0) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015, ErrorMessageConstant.SPECIAL_STAFF_NOT_BE_EMPTY);
            }
            if (Objects.equals(type, 3)) {
                // 根据标签设置，这边的校验特殊，因为他的key，是标签id数组
                for (Object object : array) {
                    JSONObject json;
                    String key = null;
                    Integer value = null;

                    try {
                        json = (JSONObject) object;
                        key = json.getString("key");
                        value = json.getInteger("value");
                    } catch (Exception e) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
                    }
                    if (key == null || Objects.equals(key, "[]")) {
                        throw new XbbException(CustomerErrorCodeEnum.API_ERROR_201035);
                    }
                    if (value != null && value < 1) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015, ErrorMessageConstant.DAYS_GREATER_ZERO);
                    }
                    if (value != null && value > 99999) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015, ErrorMessageConstant.MAXIMUM_DAYS);
                    }
                }
                continue;
            }
            for (Object object : array) {
                JSONObject json;
                Integer key;
                Integer value;
                try {
                    json = (JSONObject) object;
                    key = json.getInteger("key");
                    value = json.getInteger("value");
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
                }
                if (key == null || key < 0) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
                }
                if (value == null || value < 1) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015, ErrorMessageConstant.CUSTOMER_NUM_GREATER_ZERO);
                }
            }
        }

        Integer backType;

        try {
            backType = backRule.getInteger("backType");
            backRule.getJSONArray("sort");
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015, ErrorMessageConstant.BACKRULE_FORMAT_ERROR);
        }

        boolean isNotBackType = !Objects.equals(backType, 1) && !Objects.equals(backType, 2) && !Objects.equals(backType, 3);
        if (backType == null || isNotBackType) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015, ErrorMessageConstant.BACKRULE_TYPE_ERROR);
        }
    }

    @Override
    public Object toObject(CustomerRuleEntity rule) {
        if (rule == null) {
            return null;
        }
        Object retObject;

        try {
            retObject = JSON.parse(rule.getRuleValue());
        } catch (Exception e) {
            retObject = null;
            LOG.error("corpid:" + rule.getCorpid() + " ruleId:" + rule.getId() + "------json格式错误\n " + rule.getRuleValue());
        }
        return retObject;
    }

    @Override
    public List<String> getAllSpecialUser(Object ruleObject) {
        return OperateCheckRuleValue.checkSpecialUser(ruleObject);
    }

    /**
     * 获取规则配置中的标签Id
     *
     * @param ruleObject
     * @return
     */
    @Override
    public List<Long> getCustomerLabelIds(Object ruleObject) {
        return OperateCheckRuleValue.checkClueLabelIds(ruleObject);
    }

    @Override
    public Integer getStatus(CustomerRuleEntity customerRule) {
        if (customerRule != null) {
            return customerRule.getStatus();
        }
        return null;
    }

    @Override
    public Integer getContract(CustomerRuleEntity customerRule) {
        JSONObject retObject = (JSONObject) toObject(customerRule);
        if (retObject == null) {
            return null;
        }
        return retObject.getInteger("contract");
    }

    @Override
    public Integer getOpportunity(CustomerRuleEntity customerRule) {
        JSONObject retObject = (JSONObject) toObject(customerRule);
        if (retObject == null) {
            return null;
        }
        return retObject.getInteger("opportunity");
    }

    @Override
    public JSONArray getCustomerStatus(CustomerRuleEntity customerRule) {
        JSONObject retObject = (JSONObject) toObject(customerRule);
        if (retObject == null) {
            return null;
        }
        return retObject.getJSONArray("customerStatus");
    }

    @Override
    public Integer getType(CustomerRuleEntity customerRule) {
        JSONObject retObject = (JSONObject) toObject(customerRule);
        if (retObject == null) {
            return null;
        }
        return retObject.getInteger("type");
    }

    @Override
    public JSONArray getRestrict(CustomerRuleEntity customerRule) {
        JSONObject retObject = (JSONObject) toObject(customerRule);
        if (retObject == null) {
            return null;
        }
        return retObject.getJSONArray("restrict");
    }

    public JSONObject getBackRule(CustomerRuleEntity customerRule) {
        JSONObject retObject = (JSONObject) toObject(customerRule);
        if (retObject == null) {
            return null;
        }
        return retObject.getJSONObject("backRule");
    }

}
